﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Profile;
using Zsnd.Helpers;
using MaymuseMS.Models;
using System.Web.Security;

namespace MaymuseMS.Controllers {
    [Authorize(Roles = "systemmanagers")]
    public class UserController : CustomController {
        private IDictionary<string, string> _rolesidic;
        public IDictionary<string, String> RolesIdic {
            get {
                if (_rolesidic == null) {
                    _rolesidic = new Dictionary<string, string>();
                    _rolesidic.Add("systemmanagers", "系统管理员");
                    _rolesidic.Add("depositorymanagers", "仓库管理员");
                    _rolesidic.Add("depositoryusers", "仓库操作员");
                    _rolesidic.Add("purchasemanagers", "采购管理员");
                    _rolesidic.Add("saleusers", "销售操作员");
                }
                return _rolesidic;
            }
        }

        public ActionResult Index() {
            return View();
        }

        [HttpPost]
        public ActionResult Index(JQGridParm parm) {
            string sidx = parm.Sidx;
            string sord = parm.Sord;
            int page = parm.Page;
            int rows = parm.Rows;

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;

            int totalRecords;
            var users = Membership.GetAllUsers(pageIndex, pageSize, out totalRecords);

            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var enums = users.Cast<MembershipUser>().OrderBy(m=>m.UserName)
                .Select(m => new {
                id = m.ProviderUserKey,
                cell = new object[]{
                    m.UserName, MaymuseMS.Models.User.GetUser(m.UserName).Name, 
                    RolesIdic[Roles.GetRolesForUser(m.UserName).FirstOrDefault()]
                }
            });

            var jsonData = new {
                success = true,
                total = totalPages,
                page,
                records = totalRecords,
                rows = enums
            };
            return Json2(jsonData);
        }

        [HttpPost]
        public ActionResult Edit(string role, string name, string id) {
            var user = Membership.GetUser(Guid.Parse(id));
            if (user != null) {
                string username = user.UserName;

                MaymuseMS.Models.User.GetUser(username).Name = name;
                Roles.RemoveUserFromRoles(username, Roles.GetRolesForUser(username));
                if (Roles.RoleExists(role)) {
                    Roles.AddUserToRole(username, role);
                    return Json2(new { success = true });
                }
            }
            return Json2(new { success = false, message = errorMessage });
        }

        [HttpPost]
        public ActionResult Add(string username, string name, string role) {
            Membership.CreateUser(username, "000000");
            if (!Roles.RoleExists(role)) return Json2(new { success = false, message = errorMessage });
            Roles.AddUserToRole(username, role);
            MaymuseMS.Models.User.GetUser(username).Name = name;
            return Json2(new { success = true });
        }

        [HttpPost]
        public ActionResult Delete(string id) {
            foreach (string i in id.Split(',')) {
                MembershipUser user = Membership.GetUser(Guid.Parse(i));
                if (user == null)
                    return Json2(new { success = false, message = errorMessage });
                Membership.DeleteUser(user.UserName);
            }
            return Json2(new { success = true });
        }

        public ActionResult GetRoles() {
            var roles = Roles.GetAllRoles()
                .Select(c => new { key = c, value = RolesIdic[c] }).AsEnumerable();
            var jsonData = new { value = roles };
            return Json2(jsonData);
        }

        public ActionResult ResetPassword(string username) {
            MembershipUser u = Membership.GetUser(username);
            if (u == null) { return Json2(new { success = false, message = "用户不存在" }); }
            try {
                u.UnlockUser();
                //Membership.UpdateUser(u);
                bool b = u.ChangePassword(u.ResetPassword(), "000000");
                if (b) {
                    
                    return Json2(new { success = true });
                } else {
                    return Json2(new { success = false, message = "出错请重试！" });
                }
            } catch (MembershipPasswordException e) {
                return Json2(new { success = false, message = e.Message });
            }
        }

        private string RoleNameToCN(string roleName) {
            switch (roleName) {
                case "systemmanagers":
                    return "系统管理员";
                case "depositorymanagers":
                    return "仓库管理员";
                case "depositoryusers":
                    return "仓库操作员";
                case "purchasemanagers":
                    return "采购管理员";
                case "saleusers":
                    return "销售操作员";
                default:
                    return "无效用户";
            }
        }
    }
}
